/*
    Copyright Pat Niemeyer (pat@pat.net), 2007.
    This code is licensed under the GPL.
 */
package quickAdd.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.*;

import java.util.List;
import java.util.Collections;


/**
 * GS QuickAdd base GWT Module.
 * onModuleLoad() is the main entry point for constructing the GUI.
 */
public class QuickAdd implements EntryPoint,
    GData.SpreadsheetsListener, GData.WorksheetsListener, Auth.AuthorizationComplete
{
    // Hack: we have to do some resizing from GWT which means some hard coded padding.
    //static final int CONFIG_PAD_Y=140;
    //static final int CONFIG_PAD_X=30;

    /** Set DEBUG to true to add the debug panel */
    static private boolean DEBUG=false;
    static private TextArea debugTextArea = new TextArea();

    /** Encapsulates the GData login and token. */
    private Auth auth = new Auth(this);

    private SpreadsheetsTable ssTable = new SpreadsheetsTable("Spreadsheets");
    private SpreadsheetsTable wsTable = new SpreadsheetsTable("Worksheets");
    private List/*<GData.Spreadsheet>*/ spreadsheets;
    private List/*<GData.Worksheet>*/ worksheets;
    private CellPanel cellPanel;
    private VerticalPanel configPanel;

    public void onModuleLoad()
    {
        try {
            onModuleLoadImpl();
        } catch ( Exception e ) {
            out( e );
        }
    }

    private void onModuleLoadImpl()
    {
        // Config panel
        configPanel = new VerticalPanel();
        configPanel.setStyleName( "quickadd-MainPanel");
        configPanel.setSpacing( 8 );

        // login panel
        LoginPanel loginPanel = new LoginPanel(auth);
        configPanel.add( loginPanel );

        // Spreadsheets table
        ssTable.addTableListener( new TableListener() {
            public void onCellClicked( SourcesTableEvents sender, int row, int cell )
            {
                GData.Spreadsheet ss = (GData.Spreadsheet)spreadsheets.get(row-1);
                setWait( true );
                GData.getWorksheetsFeed( ss, auth, QuickAdd.this );
            }
        });
        configPanel.add(ssTable);

        // Worksheet table
        wsTable.addTableListener( new TableListener() {
            public void onCellClicked( SourcesTableEvents sender, int row, int cell )
            {
                GData.Worksheet ws = (GData.Worksheet)worksheets.get(row-1);
                setWait( true );
                GData.getHeaderRow( auth, ws, QuickAdd.this );
            }
        });
        configPanel.add(wsTable);

        cellPanel = new CellPanel(auth);

        HorizontalPanel rowsConfigPanel = createContextRowsPanel();
        configPanel.add( rowsConfigPanel );

        // debug area
        if ( DEBUG ) {
            debugTextArea.setVisibleLines( 15 );
            debugTextArea.setWidth("100%");
            debugTextArea.setTitle( "Debug Text Area");
            cellPanel.add( debugTextArea );
        }

        RootPanel.get("config").add( configPanel );
        RootPanel.get("cells").add( cellPanel );
        resizeCellsWindow( cellPanel.getOffsetWidth(), cellPanel.getOffsetHeight() );
    }

    private HorizontalPanel createContextRowsPanel()
    {
        HorizontalPanel rowsConfigPanel = new HorizontalPanel();
        rowsConfigPanel.setVerticalAlignment( HasVerticalAlignment.ALIGN_MIDDLE );
        rowsConfigPanel.setSpacing( 5 );
        Label lab = new Label( "Rows of context:" );
        rowsConfigPanel.add( lab );
        final TextBox rowsBox = new TextBox();
        rowsBox.setText( CellPanel.DEFAULT_CONTEXT_ROWS+"" );
        rowsBox.setVisibleLength( 2 );
        rowsBox.setStyleName( "quickadd-ContextRowsEntry");
        rowsBox.addChangeListener( new ChangeListener() {
            public void onChange( Widget sender ) {
                try {
                    cellPanel.setNumDataRows( Integer.parseInt( rowsBox.getText() ) );
                } catch ( NumberFormatException e ) {
                    rowsBox.setText( cellPanel.getNumDataRows()+"" );
                }
            }
        } );
        rowsConfigPanel.add( rowsBox );
        return rowsConfigPanel;
    }

    private static native void resizeConfigWindow( int width, int height )/*-{
        height=height+150;
        width=width+30;
        $wnd.backWidth=width;
        $wnd.backHeight=height;
        $wnd.resizeTo(width,height);
    }-*/;

    private static native void resizeCellsWindow( int width, int height )/*-{
        height=height+25;
        width=width+30;
        $wnd.frontWidth=width;
        $wnd.frontHeight=height;
        $wnd.resizeTo(width,height);
    }-*/;

    // todo: could refactor a bit here
    public void setSpreadsheets( List spreadsheets )
    {
        setWait( false );
        Collections.sort( spreadsheets );
        this.spreadsheets = spreadsheets;
        ssTable.clearData();
        for ( int i = 0; i < spreadsheets.size(); i++ )
        {
            GData.Spreadsheet spreadsheet =
                (GData.Spreadsheet)spreadsheets.get( i );
            ssTable.setRow( i, spreadsheet.title );
        }
        wsTable.clear();
        resizeConfigWindow( configPanel.getOffsetWidth(), configPanel.getOffsetHeight() );
    }
    public void setWorksheets( List worksheets )
    {
        setWait( false );
        Collections.sort( worksheets );
        this.worksheets = worksheets;
        wsTable.clearData();
        for ( int i = 0; i < worksheets.size(); i++ )
        {
            GData.Worksheet worksheet =
                (GData.Worksheet)worksheets.get( i );
            wsTable.setRow( i, worksheet.title );
        }
        resizeConfigWindow( configPanel.getOffsetWidth(), configPanel.getOffsetHeight() );
    }

    public void setWorksheetMetadata( GData.WorksheetMetadata worksheetMetadata )
    {
        setWait( false );
        cellPanel.configure( worksheetMetadata );
    }

    public void authorizationBeginning()
    {
        setWait( true ); // start wait, population of spreadsheets will clear
    }

    public void authorizationComplete()
    {
        GData.getSpreadsheetsFeed( auth, QuickAdd.this );
    }
    public void authorizationFailed() {  }

    private void setWait( boolean wait ) {
        if ( wait ) {
            configPanel.addStyleName("quickadd-Wait");
            ssTable.addStyleName("quickadd-Wait");
            wsTable.addStyleName("quickadd-Wait");
        } else {
            configPanel.removeStyleName("quickadd-Wait");
            ssTable.removeStyleName("quickadd-Wait");
            wsTable.removeStyleName("quickadd-Wait");
        }
    }

    static public void out( String text ) {
        if ( DEBUG ) {
            System.out.println( text );
            debugTextArea.setText( debugTextArea.getText() + "\n" +text );
        }
    }
    static public void out( Object o ) {
        out( o.toString() );
    }

}
